//
//  DRUrlRequest.m
//  DouBanProject
//
//  Created by lanou3g on 16/5/23.
//  Copyright © 2016年 Dragon. All rights reserved.
//

#import "DRUrlRequest.h"


#define MERROR(block) if (block) {\
    if ([NSThread isMainThread]) {\
    dispatch_async(dispatch_get_main_queue(), ^{\
        failedBlock(error);}); } }
#define MERRORJSON(block) if (block) {\
    if ([NSThread isMainThread]) {\
    dispatch_async(dispatch_get_main_queue(), ^{\
    failedBlock(err);}); } }

@implementation DRUrlRequest

/**
 *  网络请求
 *
 *  @param url          url
 *  @param par          请求参数
 *  @param type         请求方式
 *  @param successBlock 成功返回
 *  @param faileBlock   失败返回
 */
+ (void)getDataWithUrl:(NSString *)url parameters:(NSDictionary *)parameters type:(RequestType)type successBlock:(void(^)(id data))successBlock failedBlock:(void(^)(NSError *error))failedBlock{
    //如果没有url,直接返回
    if (!url) {
        if (failedBlock) {
            NSError *err = [NSError errorWithDomain:@"url为空" code:1 userInfo:nil];
            failedBlock(err);
        }
        return;
    }
    if (type == RequestTypeGet) { //执行get
        [[DRUrlRequest new] getDataWithUrl:url parameters:parameters successBlock:successBlock failedBlock:failedBlock];
    } else { //post
        [[DRUrlRequest new] postDataWithUrl:url parameters:parameters successBlock:successBlock failedBlock:failedBlock];
    }
}
//get
- (void)getDataWithUrl:(NSString *)url parameters:(NSDictionary *)parameters successBlock:(void (^)(id data))successBlock failedBlock:(void(^)(NSError *error))failedBlock{
    //拼接链接
    if (parameters) {
        //初始化字符串来接收拼接的值
        __block NSMutableString *mStr = [NSMutableString string];
        //字典block遍历
        [parameters enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            [mStr appendFormat:@"%@=%@&",key,obj];
        }];
        url = [url stringByAppendingString:[mStr substringToIndex:mStr.length-2]];
    }
    //汉子处理
    NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:set];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSError *err = nil;
        if (!error && data) {
            //解析
            id responseData = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:&err];
            //如果解析没有出错 and 解析出来数据 and 有成功的block
            if (!err && responseData && successBlock) {
                if (![NSThread isMainThread]) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        successBlock(responseData); //回到主线程 返回数据给Block
                    });
                }
                
            } else {
                if (failedBlock) {
                    NSError *err = [NSError errorWithDomain:@"解析出错" code:1 userInfo:nil];
                    if ([NSThread isMainThread]) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            failedBlock(err); //回到主线程 返回err
                        });
                    }
                    
                }
            }
        } else {
            if (failedBlock) {
                if ([NSThread isMainThread]) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        failedBlock(error); //回到主线程 返回err
                    });
                }
                
            }
        }
        
    }];
    //开启
    [task resume];
}

//post
- (void)postDataWithUrl:(NSString *)url parameters:(NSDictionary *)parameters successBlock:(void (^)(id data))successBlock failedBlock:(void(^)(NSError *error))failedBlock{
    NSMutableString *mStr = [NSMutableString string];
    if (parameters) {
        
        [parameters enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            [mStr appendString:[NSString stringWithFormat:@"%@=%@&",key,obj]];
        }];
        [mStr substringToIndex:mStr.length-2];
    }
    NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
    NSString *str1 = [mStr stringByAddingPercentEncodingWithAllowedCharacters:set].copy;

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求体
    NSData *body = [str1 dataUsingEncoding:NSUTF8StringEncoding];

    request.HTTPBody = body;
    //发送网络请求
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error){
        if (!error && data) {
            NSError *err = nil;
            id responseData = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:&err];
            if ((!err) && responseData && successBlock) {
                if (![NSThread isMainThread]) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        successBlock(responseData); //回到主线程 返回数据给Block
                        
                    });
                }
            } else {
                MERRORJSON(failedBlock)
            }
        } else {
            MERROR(failedBlock)
        }
    }];
    [task resume];
}

@end
